<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="时间范围">
              <el-date-picker v-model="searchForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键词">
              <el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4" class="text-right">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 日志列表区域 -->
    <el-card class="mt-2">
      <div class="operation-buttons">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon>
            <Plus />
          </el-icon>新建日志
        </el-button>
        <el-button type="danger" :disabled="selectedLogs.length === 0" @click="batchDelete">
          <el-icon>
            <Delete />
          </el-icon>批量删除
        </el-button>
      </div>

      <el-table :data="logList" border style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange"
        :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center', fontWeight: 'bold' }">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="logTitle" label="日志标题" align="center" />
        <el-table-column label="日志类型" align="center">
          <template #default="{ row }">
            <el-tag :type="row.logType === '事件日志' ? 'danger' : ''">
              {{ row.logType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="logTime" label="记录时间" align="center" />
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="showDetailDialog(row)">详情</el-button>
            <el-button size="small" type="primary" @click="showAddToSolutionDialog(row)">
              添加到方案
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新建日志对话框 -->
    <el-dialog v-model="createDialog.visible" :title="`新建${createDialog.type === '事件日志' ? '事件' : '普通'}日志`" width="60%"
      :close-on-click-modal="false">
      <el-form :model="logForm" :rules="logRules" ref="logFormRef" label-width="100px">
        <el-form-item label="日志类型" prop="logType">
          <el-radio-group v-model="logForm.logType">
            <el-radio-button label="事件日志">事件日志</el-radio-button>
            <el-radio-button label="普通日志">普通日志</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="日志标题" prop="logTitle">
          <el-input v-model="logForm.logTitle" placeholder="请输入日志标题" />
        </el-form-item>
        <el-form-item label="记录时间" prop="logTime">
          <el-date-picker v-model="logForm.logTime" type="datetime" placeholder="选择记录时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item v-if="logForm.logType === '事件日志'" label="事件地点">
          <el-input v-model="logForm.eventLocation" placeholder="请输入事件地点" />
        </el-form-item>
        <el-form-item v-if="logForm.logType === '事件日志'" label="经纬度">
          <el-input-number v-model="logForm.longitude" placeholder="经度" :precision="6" :step="0.000001"
            style="width: 48%; margin-right: 2%" />
          <el-input-number v-model="logForm.latitude" placeholder="纬度" :precision="6" :step="0.000001"
            style="width: 48%" />
        </el-form-item>
        <el-form-item v-if="logForm.logType === '事件日志'" label="事件时间">
          <el-date-picker v-model="logForm.eventStartTime" type="datetime" placeholder="开始时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 48%; margin-right: 2%" />
          <el-date-picker v-model="logForm.eventEndTime" type="datetime" placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss" style="width: 48%" />
        </el-form-item>
        <el-form-item v-if="logForm.logType === '事件日志'" label="处理步骤" prop="stepList">
          <div class="step-list">
            <div v-for="(step, index) in logForm.stepList" :key="index" class="step-item">
              <el-input v-model="step.description" placeholder="步骤描述" style="width: 300px; margin-right: 10px" />
              <el-date-picker v-model="step.stepTime" placeholder="步骤时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"  style="width: 300px" />
              <el-button v-if="index > 0" type="danger" text @click="removeStep(index)" style="margin-left: 10px;">
                删除
              </el-button>
            </div>
            <el-button type="primary" text @click="addStep">
              <el-icon>
                <Plus />
              </el-icon>添加步骤
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="日志内容" prop="logContent">
          <el-input v-model="logForm.logContent" type="textarea" :rows="4" placeholder="请输入日志内容" />
        </el-form-item>
        <el-form-item label="总结">
          <el-input v-model="logForm.summary" type="textarea" :rows="2" placeholder="请输入总结" />
        </el-form-item>
        <el-form-item label="附件">
          <!-- <el-upload action="" :file-list="fileList" :auto-upload="false" :on-change="handleFileChange" multiple>
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传图片、文档等附件，单个文件不超过10MB
              </div>
            </template>
          </el-upload> -->
          <UploadFile v-model:file-ids="logForm.files" :fileList="fileList" type="file" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmCreate">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 日志详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="detailDialog.data.logTitle" width="70%"
      :close-on-click-modal="false">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="日志标题">
          <el-tag>
            {{ detailDialog.data.logTitle }}
          </el-tag>
        </el-descriptions-item>
        <!-- <el-descriptions-item label="日志类型">
          <el-tag :type="detailDialog.data.logType === '事件日志' ? 'danger' : ''">
            {{ detailDialog.data.logType }}
          </el-tag>
        </el-descriptions-item> -->
        <el-descriptions-item label="记录时间">
          {{ detailDialog.data.logTime }}
        </el-descriptions-item>
        <el-descriptions-item v-if="detailDialog.data.eventLocation" label="事件地点">
          {{ detailDialog.data.eventLocation }}
        </el-descriptions-item>
        <el-descriptions-item v-if="detailDialog.data.longitude && detailDialog.data.latitude" label="经纬度">
          {{ detailDialog.data.longitude }}, {{ detailDialog.data.latitude }}
        </el-descriptions-item>
        <el-descriptions-item v-if="detailDialog.data.eventStartTime" label="事件时间" :span="2">
          {{ detailDialog.data.eventStartTime }} 至 {{ detailDialog.data.eventEndTime || '进行中' }}
        </el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">处理步骤</el-divider>
      <el-timeline v-if="detailDialog.data.stepList?.length">
        <el-timeline-item v-for="(step, index) in detailDialog.data.stepList" :key="index" :timestamp="step.stepTime">
          {{ step.description }}
        </el-timeline-item>
      </el-timeline>
      <el-empty v-else description="无处理步骤" :image-size="60" />

      <el-divider content-position="left">日志内容</el-divider>
      <div class="log-content">{{ detailDialog.data.logContent }}</div>

      <el-divider v-if="detailDialog.data.summary" content-position="left">总结</el-divider>
      <div v-if="detailDialog.data.summary" class="log-summary">
        {{ detailDialog.data.summary }}
      </div>

      <el-divider v-if="detailDialog.data.fileList?.length" content-position="left">附件</el-divider>
      <div v-if="detailDialog.data.fileList?.length" class="file-list">
        <div v-for="file in detailDialog.data.fileList" :key="file.fileId" class="file-item">
          <el-link type="primary" :href="file.filePath" target="_blank">
            {{ file.originalFileName }}
          </el-link>
          <span class="file-size">({{ formatFileSize(file.fileSize) }})</span>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialog.visible = false">关闭</el-button>
          <el-button v-if="detailDialog.data.logType === '事件日志'" type="primary"
            @click="showAddToSolutionDialog(detailDialog.data)">
            添加到方案库
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加到方案库对话框 -->
    <el-dialog v-model="solutionDialog.visible" title="添加到方案库" width="50%" :close-on-click-modal="false">
      <el-form :model="solutionForm" label-width="100px">
        <el-form-item label="方案名称" prop="solutionName">
          <el-input v-model="solutionForm.solutionName" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="solutionForm.categoryId" placeholder="请选择所属分类" style="width: 100%">
            <el-option v-for="category in categoryOptions" :key="category.id" :label="category.name"
              :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="方案描述" prop="description">
          <el-input v-model="solutionForm.description" type="textarea" :rows="3" placeholder="请输入方案描述" />
        </el-form-item>
        <el-form-item label="包含步骤">
          <el-checkbox-group v-model="solutionForm.selectedSteps">
            <el-checkbox v-for="(step, index) in solutionDialog.data.stepList" :key="index" :label="step.stepId">
              步骤{{ index + 1 }}: {{ step.description }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="solutionDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddToSolution">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import UploadFile from '@/components/UploadFile'

import {
  getDispatchLogList,
  getDispatchLogDetail,
  addDispatchLog,
  deleteDispatchLog,
  addToSolutionLibrary,
  getLogCategory
} from '@/api/dispatch/affair/dispatch_log'

// 加载状态
const loading = ref(false)
const logFormRef = ref(null)

// 日志类型选项
const logTypeOptions = ref([
  { value: '事件日志', label: '事件日志' },
  { value: '普通日志', label: '普通日志' }
])

// 分类选项
const categoryOptions = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  logType: '',
  startTime: '',
  endTime: '',
  keyword: ''
})

// 搜索表单
const searchForm = reactive({
  dateRange: [],
  logType: '',
  keyword: ''
})

// 日志列表数据
const logList = ref([])
const total = ref(0)

// 选中的日志
const selectedLogs = ref([])

// 文件列表
const fileList = ref([])

// 新建日志对话框
const createDialog = reactive({
  visible: false,
  type: '事件日志'
})

// 日志表单
const logForm = reactive({
  logType: '事件日志',
  logTitle: '',
  logTime: '',
  logContent: '',
  summary: '',
  eventLocation: '',
  longitude: null,
  latitude: null,
  eventStartTime: '',
  eventEndTime: '',
  stepList: [
    {
      stepTime: '',
      description: ''
    }
  ],
  files: ''
})

// 表单验证规则
const logRules = reactive({
  logTitle: [
    { required: true, message: '请输入日志标题', trigger: 'blur' }
  ],
  logTime: [
    { required: true, message: '请选择记录时间', trigger: 'change' }
  ],
  logContent: [
    { required: true, message: '请输入日志内容', trigger: 'blur' }
  ],
  stepList: [
    {
      validator: (rule, value, callback) => {
        if (logForm.logType === '事件日志') {
          const isValid = value.every(
            step => step.stepTime && step.description
          )
          if (!isValid) {
            callback(new Error('请填写完整的处理步骤'))
          }
        }
        callback()
      },
      trigger: 'change'
    }
  ]
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: {}
})

// 添加到方案库对话框
const solutionDialog = reactive({
  visible: false,
  data: null
})

const solutionForm = reactive({
  scheduleLogId: '',
  solutionName: '',
  categoryId: '',
  description: '',
  selectedSteps: []
})

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取分类选项
    const categoryRes = await getLogCategory()
    categoryOptions.value = categoryRes.data

    // 获取日志列表
    await fetchLogList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取日志列表
const fetchLogList = async () => {
  try {
    loading.value = true

    // 处理查询参数
    const params = { ...queryParams }
    if (searchForm.dateRange?.length === 2) {
      params.startTime = searchForm.dateRange[0]
      params.endTime = searchForm.dateRange[1]
    }
    if (searchForm.logType) {
      params.logType = searchForm.logType
    }
    if (searchForm.keyword) {
      params.keyword = searchForm.keyword
    }

    const res = await getDispatchLogList(params)
    logList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取日志列表失败:', error)
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchLogList()
}

// 重置查询条件
const resetQuery = () => {
  searchForm.dateRange = []
  searchForm.logType = ''
  searchForm.keyword = ''
  handleQuery()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchLogList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchLogList()
}

// 处理表格选择
const handleSelectionChange = (selection) => {
  selectedLogs.value = selection.map(item => item.scheduleLogId)
}

// 显示新建对话框
const showCreateDialog = () => {
  createDialog.visible = true
  resetLogForm()
}

// 重置日志表单
const resetLogForm = () => {
  logForm.logType = '事件日志'
  logForm.logTitle = ''
  logForm.logTime = ''
  logForm.logContent = ''
  logForm.summary = ''
  logForm.eventLocation = ''
  logForm.longitude = null
  logForm.latitude = null
  logForm.eventStartTime = ''
  logForm.eventEndTime = ''
  logForm.stepList = [
    {
      stepTime: '',
      description: ''
    }
  ]
  logForm.files = ''
  fileList.value = []
}

// 添加处理步骤
const addStep = () => {
  logForm.stepList.push({
    stepTime: '',
    description: ''
  })
}

// 删除处理步骤
const removeStep = (index) => {
  logForm.stepList.splice(index, 1)
}

// 处理文件变化
const handleFileChange = (file) => {
  fileList.value.push(file)
}

// 确认新建日志
const confirmCreate = async () => {
  try {
    await logFormRef.value.validate()

    await addDispatchLog(logForm)
    ElMessage.success('日志创建成功')
    createDialog.visible = false
    fetchLogList()
  } catch (error) {
    console.error('创建日志失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 显示详情对话框
const showDetailDialog = async (row) => {
  try {
    loading.value = true
    const res = await getDispatchLogDetail(row.scheduleLogId)
    detailDialog.data = res.data
    detailDialog.visible = true
  } catch (error) {
    console.error('获取日志详情失败:', error)
    ElMessage.error('获取日志详情失败')
  } finally {
    loading.value = false
  }
}

// 显示添加到方案库对话框
const showAddToSolutionDialog = (log) => {
  solutionDialog.data = log
  solutionForm.scheduleLogId = log.scheduleLogId
  solutionForm.solutionName = log.logTitle + '处理方案'
  solutionForm.categoryId = ''
  solutionForm.description = log.summary || ''
  solutionForm.selectedSteps = log.stepList?.map(step => step.stepId) || []
  solutionDialog.visible = true
}

// 确认添加到方案库
const confirmAddToSolution = async () => {
  try {
    if (!solutionForm.solutionName) {
      ElMessage.warning('请输入方案名称')
      return
    }
    if (!solutionForm.categoryId) {
      ElMessage.warning('请选择所属分类')
      return
    }

    const data = {
      scheduleLogId: solutionForm.scheduleLogId,
      solutionName: solutionForm.solutionName,
      categoryId: solutionForm.categoryId,
      description: solutionForm.description
    }

    await addToSolutionLibrary(data)
    ElMessage.success('添加到方案库成功')
    solutionDialog.visible = false
  } catch (error) {
    console.error('添加到方案库失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 删除日志
const deleteLog = (logId) => {
  ElMessageBox.confirm('确定要删除该日志吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDispatchLog(logId)
      ElMessage.success('删除成功')
      fetchLogList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 批量删除
const batchDelete = () => {
  if (selectedLogs.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  ElMessageBox.confirm('确定要删除选中的日志吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDispatchLog(selectedLogs.value.join(','))
      ElMessage.success('删除成功')
      selectedLogs.value = []
      fetchLogList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return size + 'KB'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + 'MB'
  } else {
    return (size / (1024 * 1024)).toFixed(2) + 'GB'
  }
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-card :deep(.el-form-item) {
  margin-bottom: 0;
}

.operation-buttons {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.log-content,
.log-summary {
  white-space: pre-wrap;
  line-height: 1.6;
}

.file-list {
  margin-top: 10px;
}

.file-item {
  margin-bottom: 8px;
}

.file-size {
  margin-left: 8px;
  color: #909399;
}

.step-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.step-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>